package com.ljchen.formalProject.util;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ljchen.formalProject.model.dto.UserDto;
import com.ljchen.formalProject.model.po.User;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Jwt工具类（这边采用Auth0-jwt）
 *
 * @author chenlinjun
 * @date 2022/11/22
 */
public class JwtUtil {

    private static String SECRET_KEY = "$KjDvh&CuRwDqH^zb4#%z7ZsoNibNJfN";

    private static final long TOKEN_EXPIRE_TIME = (24 * 60 * 60 * 1000) * 30L;

    /**
     * 生成令牌
     *
     * @param userDto 用户dto
     * @return {@link String}
     */
    public static String generateToken(User user) {
        Date expireTime = new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        JWTCreator.Builder jwt = JWT.create();
        return jwt.withIssuer("auth0")
                .withIssuedAt(new Date())
                .withNotBefore(new Date())
                .withExpiresAt(expireTime)
                .withClaim("userId", user.getId())
                .withClaim("username", user.getUsername())
                .withClaim("userEmail", user.getEmail())
                .withClaim("expireTime",expireTime)
                .sign(algorithm);
    }

    /**
     * 验证令牌
     *
     * @param token 令牌
     * @return boolean
     */
    public static boolean verifyToken(String token){
        Algorithm algorithm=Algorithm.HMAC256(SECRET_KEY);
        JWTVerifier verifier=JWT.require(algorithm).withIssuer("auth0").build();
        verifier.verify(token);
        return true;
    }

    /**
     * 得到用户id
     *
     * @param token 令牌
     * @return {@link String}
     */
    public static String getUserId(String token){
        DecodedJWT decodedJWT=JWT.decode(token);
        return decodedJWT.getClaim("userId").asString();
    }


    /**
     * 获得用户名
     *
     * @param token 令牌
     * @return {@link String}
     */
    public static String getUsername(String token){
        DecodedJWT decodedJWT=JWT.decode(token);
        return decodedJWT.getClaim("username").asString();
    }


    /**
     * 校验token是否过期
     *
     * @param token 令牌
     * @return boolean
     */
    public static boolean judgeTokenExpire(String token){
        DecodedJWT decodedJWT=JWT.decode(token);
        Date expireTime=decodedJWT.getExpiresAt();
        if (DateTime.now().isBefore(expireTime)){
            return true;
        }
        return false;
    }

}
